<template>
  <view class="daily-cost-container" @click="handleContainerClick">
    <!-- 搜索筛选 -->
    <uni-section title="搜索筛选" type="line"></uni-section>
    <view class="search-section">
      <view class="search-row">
        <view class="search-item full">
          <view class="input-with-icon" :class="{ focused: projectFocused }" @click="showProjectPicker">
            <uni-icons type="folder" size="20" color="#999"></uni-icons>
            <view class="search-input inner" :class="{ placeholder: !search.projectName }">
              {{ search.projectName || '请选择项目' }}
            </view>
            <uni-icons v-if="search.projectName" type="closeempty" size="18" color="#bbb"
              @click.stop="clearProjectName"></uni-icons>
            <uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
          </view>
        </view>
      </view>
      <view class="search-row">
        <view class="search-item full">
          <view class="date-input" :class="{ focused: dateFocused }">
            <uni-icons type="calendar" size="20" color="#999"></uni-icons>
            <picker mode="date" :value="search.date" @change="onDateChange">
              <view class="search-input inner" :class="{ placeholder: !search.date }">
                {{ search.date || '请选择分析日期' }}
              </view>
            </picker>
            <uni-icons v-if="search.date" type="closeempty" size="18" color="#bbb" @click="clearDate"></uni-icons>
          </view>
        </view>
      </view>
      <view class="search-actions"></view>
    </view>

    <!-- 成本分析列表 -->
    <view class="section-header">
      <uni-section title="日成本分析列表" type="line"></uni-section>
      <view class="total-display">
        <text class="total-text">共 {{ total }} 条记录</text>
      </view>
    </view>
    <view class="cost-list">
      <view class="cost-item" @click.stop="handleView(item)" v-for="item in costList" :key="item.id">
        <!-- 成本分析信息容器 -->
        <view class="cost-content">
          <!-- 头部：左侧分析日期 加粗；右侧创建时间 -->
          <view class="cost-header">
            <text class="date-text">{{ getDateOnly(item.reportDate) + '日成本分析' || '-' }}</text>
            <text class="create-time">{{ changeTime(item.createTime) || '-' }}</text>
          </view>

          <!-- 中部：左右两块 -->
          <view class="cost-meta">
            <view class="meta-left">

              <view class="meta-item">
                <text class="meta-label">填报人：</text>
                <text class="meta-value">{{ item.createBy || '-' }}</text>
              </view>

              <!-- <view class="meta-item">
                <text class="meta-label">当日利润率</text>
                <text class="meta-value">{{ item.dailyProfitRate || '-' }}</text>
              </view> -->
            </view>
            <view class="meta-right">
              <view class="meta-item">
                <text class="meta-label">当日利润率：</text>
                <text class="meta-value">{{ item.dailyProfitRate != null
                  ? Number(item.dailyProfitRate * 100).toFixed(2) + "%"
                  : "--" }}</text>
              </view>

              <!-- 

              <view class="meta-item">
                <text class="meta-label">其他成本</text>
                <text class="meta-value">¥{{ formatAmount(item.otherCost) || '-' }}</text>
              </view> -->
            </view>
          </view>

          <!-- 利润信息独占一行展示 -->
          <view class="profit-row">
            <text class="meta-label" style="width: 230rpx;">累计实现利润率：</text>
            <text class="meta-value profit-amount">
              {{ item.totalProfitRate != null
                ? Number(item.totalProfitRate * 100).toFixed(2) + "%"
                : "--" }}
            </text>
          </view>
          <view class="profit-row">
            <text class="meta-label">所属项目：</text>
            <text class="meta-value profit-amount">
              {{ getProjectNameById(item.projectId) || '-' }}
            </text>
          </view>

          <!-- 底部操作按钮 -->
          <view class="cost-actions">
            <view class="action-btn view-btn" @click.stop="handleView(item)">
              <uni-icons type="eye" size="16" color="#007AFF"></uni-icons>
              <text>详情</text>
            </view>
            <!-- <view class="action-btn edit-btn" @click.stop="handleEdit(item)">
              <uni-icons type="compose" size="16" color="#FF9500"></uni-icons>
              <text>修改</text>
            </view> -->
            <view v-if="hasPermi('production:projectProfitReport:remove')" class="action-btn delete-btn"
              @click.stop="handleDelete(item)">
              <uni-icons type="trash" size="16" color="#FF3B30"></uni-icons>
              <text>删除</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 分页控制 -->
    <view class="pagination-container" v-if="costList.length > 0">
      <!-- 分页信息 -->
      <view class="pagination-info">
        <text class="pagination-text">
          第 {{ pageNum }} 页，共 {{ Math.ceil(total / pageSize) }} 页，显示 {{ costList.length }} / {{ total }} 条
        </text>
      </view>

      <!-- 分页按钮 -->
      <view class="pagination-buttons" v-if="Math.ceil(total / pageSize) > 1">
        <button class="page-btn prev-btn" :class="{ disabled: pageNum <= 1 }" :disabled="pageNum <= 1"
          @click="goToPage(pageNum - 1)">
          <uni-icons type="arrowleft" size="16" color="currentColor"></uni-icons>
          <text>上一页</text>
        </button>

        <view class="page-numbers">
          <button v-for="page in getPageNumbers()" :key="page" class="page-number"
            :class="{ active: page === pageNum, ellipsis: page === '...' }" :disabled="page === '...'"
            @click="page !== '...' && goToPage(page)">
            {{ page }}
          </button>
        </view>

        <button class="page-btn next-btn" :class="{ disabled: pageNum >= Math.ceil(total / pageSize) }"
          :disabled="pageNum >= Math.ceil(total / pageSize)" @click="goToPage(pageNum + 1)">
          <text>下一页</text>
          <uni-icons type="arrowright" size="16" color="currentColor"></uni-icons>
        </button>
      </view>
    </view>

    <!-- 项目选择弹窗 -->
    <uni-popup ref="projectPopup" type="bottom" :safe-area="false">
      <view class="project-picker">
        <view class="picker-header">
          <text class="picker-title">选择项目</text>
          <uni-icons type="closeempty" size="20" color="#999" @click="closeProjectPicker"></uni-icons>
        </view>
        <view class="picker-content">
          <view class="project-list">
            <view class="project-item" v-for="project in projectList" :key="project.id" @click="selectProject(project)"
              :class="{ selected: search.projectId === project.id }">
              <view class="project-info">
                <text class="project-name">{{ project.projectName || project.name }}</text>
                <text class="project-desc">{{ project.projectDesc || project.description || '' }}</text>
              </view>
              <uni-icons v-if="search.projectId === project.id" type="checkmarkempty" size="20"
                color="#007AFF"></uni-icons>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { listAllProjectContractInfo, listProjectProfitReport, delProjectProfitReport, getProjectProfitReport } from '@/api/production/index'

export default {
  data() {
    return {
      // 搜索相关
      search: {
        projectName: '',
        projectId: '',
        date: ''
      },
      projectFocused: false,
      dateFocused: false,

      // 项目列表
      projectList: [],
      projectOptions: [],
      projectIdToName: {},

      // 列表相关
      costList: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
    }
  },
  onLoad() {
    this.loadProjectList()
    this.loadCostList()
  },
  onShow() {
    // 页面显示时刷新列表
    this.loadCostList()
  },
  methods: {
    /** 根据项目ID获取项目名称 */
    getProjectNameById(projectId) {
      if (projectId == null || projectId === '') return ''
      // 先从映射表读取，O(1)
      const key = String(projectId)
      const nameFromMap = this.projectIdToName && this.projectIdToName[key]
      if (nameFromMap) return nameFromMap
      // 兼容：如果还没构建映射，尝试从列表里查找
      const list = this.projectOptions && this.projectOptions.length ? this.projectOptions : this.projectList
      const found = Array.isArray(list) ? list.find(p => String(p.id) === key || String(p.projectId) === key) : null
      return found ? (found.projectName || found.name || '') : String(projectId)
    },
    changeTime(time) {
      if (!time) return '';
      const date = new Date(time);
      if (isNaN(date.getTime())) return time;
      const pad = n => n < 10 ? '0' + n : n;
      const y = date.getFullYear();
      const m = pad(date.getMonth() + 1);
      const d = pad(date.getDate());
      const h = pad(date.getHours());
      const min = pad(date.getMinutes());
      const s = pad(date.getSeconds());
      return `${y}-${m}-${d} ${h}:${min}:${s}`;
    },
    // 只保留年月日
    getDateOnly(datetime) {
      if (!datetime) return '';
      // 兼容字符串和Date对象
      const str = typeof datetime === 'string' ? datetime : this.changeTime(datetime);
      // 匹配 yyyy-MM-dd
      const match = str.match(/^\d{4}-\d{2}-\d{2}/);
      return match ? match[0] : str;
    },
    // 格式化金额
    formatAmount(amount) {
      if (amount == null || amount === '') return '0.00';
      const num = parseFloat(amount);
      if (isNaN(num)) return '0.00';
      return num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    },
    // 项目相关方法
    async loadProjectList() {
      try {
        // 调用项目接口
        const response = await listAllProjectContractInfo()
        const raw = (response && (response.rows || response.data)) || []
        const options = raw.map(p => ({
          id: p.id != null ? p.id : p.projectId,
          projectName: p.projectName != null ? p.projectName : (p.name != null ? p.name : ''),
          _raw: p
        })).filter(o => o.id != null)
        this.projectOptions = options
        this.projectList = options
        // 构建快速查找表（字符串键，兼容数字/字符串ID）
        const map = {}
        options.forEach(o => {
          map[String(o.id)] = o.projectName || ''
        })
        this.projectIdToName = map
      } catch (error) {
        console.error('获取项目列表失败:', error)
        uni.showToast({
          title: '获取项目列表失败',
          icon: 'none'
        })
      }
    },

    showProjectPicker() {
      this.$refs.projectPopup.open()
    },

    closeProjectPicker() {
      this.$refs.projectPopup.close()
    },

    selectProject(project) {
      this.search.projectId = project.id
      this.search.projectName = project.projectName || project.name
      this.closeProjectPicker()
      this.handleSearch()
    },

    // 搜索相关方法
    clearProjectName() {
      this.search.projectName = ''
      this.search.projectId = ''
      this.handleSearch()
    },
    clearDate() {
      this.search.date = ''
      this.handleSearch()
    },
    onDateChange(e) {
      this.search.date = e.detail.value
      this.handleSearch()
    },

    // 搜索操作
    handleSearch() {
      this.pageNum = 1
      this.costList = [] // 清空当前列表
      this.loadCostList()
    },
    handleReset() {
      this.search = {
        projectName: '',
        projectId: '',
        date: ''
      }
      this.projectFocused = false
      this.dateFocused = false
      this.pageNum = 1
      this.costList = [] // 清空当前列表
      this.loadCostList()
    },

    // 列表相关方法
    async loadCostList() {
      try {
        // 构建查询参数
        const query = {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }

        // 添加搜索条件
        if (this.search.projectId) {
          query.projectId = this.search.projectId
        }
        if (this.search.date) {
          query.reportDate = this.search.date
        }

        // 调用接口获取数据
        const response = await listProjectProfitReport(query)

        if (response.rows && response.rows.length > 0) {
          this.costList = response.rows
          this.total = response.total || 0
        } else {
          this.costList = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取成本分析列表失败:', error)
        uni.showToast({
          title: '获取数据失败',
          icon: 'none'
        })
      }
    },

    // 分页相关方法
    goToPage(page) {
      if (page < 1 || page > Math.ceil(this.total / this.pageSize)) return

      this.pageNum = page
      this.loadCostList()
    },

    getPageNumbers() {
      const totalPages = Math.ceil(this.total / this.pageSize)
      const currentPage = this.pageNum
      const pages = []

      if (totalPages <= 7) {
        // 总页数少于等于7页，显示所有页码
        for (let i = 1; i <= totalPages; i++) {
          pages.push(i)
        }
      } else {
        // 总页数大于7页，显示省略号
        if (currentPage <= 4) {
          // 当前页在前4页
          for (let i = 1; i <= 5; i++) {
            pages.push(i)
          }
          pages.push('...')
          pages.push(totalPages)
        } else if (currentPage >= totalPages - 3) {
          // 当前页在后4页
          pages.push(1)
          pages.push('...')
          for (let i = totalPages - 4; i <= totalPages; i++) {
            pages.push(i)
          }
        } else {
          // 当前页在中间
          pages.push(1)
          pages.push('...')
          for (let i = currentPage - 1; i <= currentPage + 1; i++) {
            pages.push(i)
          }
          pages.push('...')
          pages.push(totalPages)
        }
      }

      return pages
    },

    // 操作相关
    handleView(item) {
      uni.navigateTo({
        url: `/pages/work/production/daily-cost-detail?id=${item.id}`
      })
    },
    handleEdit(item) {
      uni.navigateTo({
        url: `/pages/work/production/daily-cost-form?id=${item.id}`
      })
    },
    handleDelete(item) {
      uni.showModal({
        title: '确认删除',
        content: `确定要删除"${this.getDateOnly(item.reportDate)}日成本分析"吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              // 显示加载状态
              uni.showLoading({
                title: '删除中...',
                mask: true
              })

              // 调用删除接口
              await delProjectProfitReport(item.id)

              // 隐藏加载状态
              uni.hideLoading()

              // 显示成功提示
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              })

              // 刷新列表
              this.loadCostList()
            } catch (error) {
              // 隐藏加载状态
              uni.hideLoading()

              console.error('删除失败:', error)

              // 显示错误提示
              uni.showToast({
                title: error.message || '删除失败',
                icon: 'none',
                duration: 2000
              })
            }
          }
        }
      })
    },

    // 容器点击事件
    handleContainerClick() {
      // 可以在这里添加其他容器点击逻辑
    }
  }
}
</script>

<style lang="scss" scoped>
.daily-cost-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 搜索区域样式 */
.search-section {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.search-row {
  display: flex;
  margin-bottom: 20rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.search-item {
  flex: 1;
  margin-right: 20rpx;

  &:last-child {
    margin-right: 0;
  }
}

.search-item.full {
  flex: 1 1 100%;
  margin-right: 0;
}

.input-with-icon,
.date-input {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border: 2rpx solid #e9ecef;
  border-radius: 12rpx;
  padding: 20rpx;
  transition: all 0.3s ease;

  &.focused {
    border-color: #007AFF;
    background: #fff;
    box-shadow: 0 0 0 6rpx rgba(0, 122, 255, 0.1);
  }
}

.search-input {
  flex: 1;
  margin: 0 20rpx;
  font-size: 28rpx;
  color: #333;

  &.inner {
    background: transparent;
    border: none;
    outline: none;
  }

  &.placeholder {
    color: #999;
  }
}

.search-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 30rpx;
}

.search-btn {
  flex: 1;
  margin: 0 8rpx;
  padding: 16rpx 0;
  border-radius: 8rpx;
  font-size: 24rpx;
  font-weight: 500;
  border: none;
  transition: all 0.3s ease;

  &:first-child {
    margin-left: 0;
  }

  &:last-child {
    margin-right: 0;
  }

  &.primary {
    background: #007AFF;
    color: white;

    &:active {
      background: #0056b3;
    }
  }

  &:not(.primary) {
    background: #6c757d;
    color: white;

    &:active {
      background: #545b62;
    }
  }
}

/* 列表区域样式 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx;
  margin-bottom: 20rpx;
}

.total-display {
  .total-text {
    font-size: 24rpx;
    color: #666;
  }
}

.cost-list {
  padding: 0 30rpx;
}

.cost-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: flex-start;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  }
}

.cost-content {
  flex: 1;
}

/* 头部和元信息布局 */
.cost-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.date-text {
  font-size: 32rpx;
  font-weight: 700;
  color: #333;
}

.create-time {
  font-size: 24rpx;
  color: #666;
}

.cost-meta {
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
  margin-bottom: 6rpx;
}

/* 利润信息独占一行 */
.profit-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 6rpx;
}

.profit-row .meta-value {
  flex: 1;
  min-width: 0;
  white-space: normal;
  word-break: break-word;
}

.meta-left,
.meta-right {
  flex: 1;
}

.meta-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12rpx;
}

.meta-label {
  width: 160rpx;
  flex: 0 0 160rpx;
  font-size: 26rpx;
  color: #666;
  white-space: nowrap;
}

.meta-value {
  flex: 1;
  min-width: 0;
  font-size: 28rpx;
  color: #333;
  white-space: normal;
  word-break: break-word;
}


.profit-amount {
  font-weight: 600;
  font-size: 30rpx;
}

.cost-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20rpx;
  gap: 16rpx;
}

.action-btn {
  display: flex;
  align-items: center;
  padding: 0;
  margin: 0;
  font-size: 24rpx;
  background: none;
  border: none;
  box-shadow: none;
  outline: none;

  uni-icons {
    margin-right: 6rpx;
  }

  &.view-btn {
    color: #007AFF;
  }

  &.edit-btn {
    color: #FF9500;
  }

  &.delete-btn {
    color: #FF3B30;
  }
}

/* 分页样式 */
.pagination-container {
  margin-top: 30rpx;
  padding: 20rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.pagination-info {
  text-align: center;
  margin-bottom: 20rpx;
}

.pagination-text {
  font-size: 24rpx;
  color: #666;
  font-weight: 500;
}

.pagination-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  flex-wrap: nowrap;
  overflow-x: auto;
  padding: 10rpx 0;
}

.page-btn {
  display: flex;
  align-items: center;
  gap: 6rpx;
  padding: 12rpx 16rpx;
  font-size: 24rpx;
  font-weight: 500;
  border: 2rpx solid #e1e5e9;
  background: #fff;
  color: #333;
  border-radius: 8rpx;
  min-width: 100rpx;
  justify-content: center;
  transition: all 0.3s ease;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
  flex-shrink: 0;
  white-space: nowrap;
}

.page-btn:not(.disabled):active {
  background: #f8f9fa;
  border-color: #007AFF;
  color: #007AFF;
  transform: translateY(1rpx);
  box-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
}

.page-btn.disabled {
  color: #c8c9cc;
  border-color: #f2f3f5;
  background: #fafbfc;
  box-shadow: none;
}

.page-numbers {
  display: flex;
  gap: 6rpx;
  align-items: center;
  margin: 0 12rpx;
  flex-shrink: 0;
}

.page-number {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12rpx 16rpx;
  font-size: 24rpx;
  font-weight: 500;
  border: 2rpx solid #e1e5e9;
  background: #fff;
  color: #333;
  border-radius: 8rpx;
  min-width: 50rpx;
  text-align: center;
  transition: all 0.3s ease;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
  flex-shrink: 0;
}

.page-number:not(.ellipsis):not(.active):active {
  background: #f8f9fa;
  border-color: #007AFF;
  color: #007AFF;
  transform: translateY(1rpx);
  box-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
}

.page-number.active {
  background: linear-gradient(135deg, #007AFF 0%, #5AC8FA 100%);
  color: #fff;
  border-color: #007AFF;
  box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
  transform: translateY(-1rpx);
}

.page-number.ellipsis {
  border: none;
  background: transparent;
  color: #999;
  cursor: default;
  box-shadow: none;
  font-weight: 400;
  padding: 12rpx 8rpx;
  min-width: auto;
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .pagination-buttons {
    gap: 6rpx;
    padding: 8rpx 0;
  }

  .page-btn {
    padding: 10rpx 12rpx;
    font-size: 22rpx;
    min-width: 80rpx;
    gap: 4rpx;
  }

  .page-number {
    padding: 10rpx 12rpx;
    font-size: 22rpx;
    min-width: 40rpx;
  }

  .page-numbers {
    margin: 0 8rpx;
    gap: 4rpx;
  }

  .pagination-text {
    font-size: 22rpx;
  }
}

@media (max-width: 600rpx) {
  .pagination-buttons {
    gap: 4rpx;
  }

  .page-btn {
    padding: 8rpx 10rpx;
    font-size: 20rpx;
    min-width: 70rpx;
  }

  .page-number {
    padding: 8rpx 10rpx;
    font-size: 20rpx;
    min-width: 35rpx;
  }

  .page-numbers {
    margin: 0 6rpx;
    gap: 3rpx;
  }
}

/* 项目选择弹窗样式 */
.project-picker {
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 60vh;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.picker-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.picker-content {
  max-height: 50vh;
  overflow-y: auto;
}

.project-list {
  padding: 0 30rpx 30rpx;
}

.project-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
  transition: background-color 0.3s ease;

  &:last-child {
    border-bottom: none;
  }

  &:active {
    background-color: #f8f9fa;
  }

  &.selected {
    background-color: rgba(0, 122, 255, 0.05);
  }
}

.project-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.project-name {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 8rpx;
}

.project-desc {
  font-size: 24rpx;
  color: #666;
  line-height: 1.4;
}
</style>
